<template>
<div class="page-container">
    <div class="toolbar">
        <el-form :inline="true">
            <el-row class="search-button mt20">

              <el-form-item>
                <kt-button icon="fa fa-plus" :label="$t('action.add')" type="primary" @click="handleAdd" />
              </el-form-item>
            </el-row>

        </el-form>
    </div>
    <el-dialog :title="operation" :visible.sync="areaFormVisible" width="40%" :close-on-click-modal="false">
        <el-form :model="areaForm" ref="areaForm" :rules="rules" label-width="100px" :size="size" label-position="right">
            <el-row class="searchDialog-input">
                <el-form-item label="区域编码：" prop="areaCode" :label-width="formLabelWidth">
                    <el-input v-model="areaForm.areaCode" autocomplete="off" placeholder="1-20个字符，支持字母、数字、下划线"></el-input>
                </el-form-item>
                <el-form-item label="区域名称：" prop="areaName" :label-width="formLabelWidth">
                    <el-input v-model="areaForm.areaName" autocomplete="off" placeholder="1-20个字符"></el-input>
                </el-form-item>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="areaFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAreaForm('areaForm')">确 定</el-button>
        </div>
    </el-dialog>

  <!--表格内容栏-->
  <Jic-table
    :height="350"
    :data="pageResult"
    :columns="filterColumns"
    @findPage="findPage"
    :showBatchDelete="false"
    :showDetailOperation="false"
    :showDeleteOperation="true"
    @handleEdit="handleEdit"
    @handleDelete="handleDelete"
    ref="JicTable">
  </Jic-table>
</div>
</template>

<script>
import JicTable from "@/views/Core/JicTable";
import KtButton from "@/views/Core/KtButton";
export default {
    components: {
        JicTable,
        KtButton
    },
    data() {
        return {
            pageResult: {},
            operation:null,
            size: "small",
            filterColumns: [],
            columns: [],
            areaFormVisible: false, //新增编辑弹框
            areaForm: {
                areaCode: "", //区域编码
                merchantId: "", //所属商家
                areaName: "", //区域名称
                desc: "",
                coverageType: 1,
                cityIds: []
            },
            merchantList: [],
            rules: {

              areaCode: [
                { required: true, message: "请输入区域编码", trigger: "blur" },
                {
                  min: 1,
                  max: 20,
                  message: "长度在 1 到 20 个字符",
                  trigger: "blur",
                }
              ],
              areaName: [
                { required: true, message: "请输入区域名称", trigger: "blur" },
                {
                  min: 1,
                  max: 20,
                  message: "长度在 1 到 20 个字符",
                  trigger: "blur",
                }
              ],
            },
            formLabelWidth: "120px",
            checkAll: false,
            isIndeterminate: true,
            provinceList: [],
            filters: {
                start: 1,
                limit: 10
            }
        };
    },
    mounted() {
        this.initColumns();
        this.findPage();
        this.initData();
    },
    methods: {
        // 处理表格列过滤显示
        initColumns: function () {
            this.columns = [{
                    prop: "areaCode",
                    label: "区域编码",
                    minWidth: 120
                },
                {
                    prop: "areaName",
                    label: "区域名称",
                    minWidth: 120
                },
                {
                    prop: "merchantName",
                    label: "所属商家",
                    minWidth: 120
                }
            ];
            var temp = [];

            $.each(this.columns, function (key, val) {
                temp.push(val);
            });
            this.filterColumns = temp;
        },
      // 显示新增界面
      handleAdd: function () {

        this.areaFormVisible = true;
        this.operation = "新增";
        this.$refs['areaForm'].resetFields();
        this.areaForm={};

      },
        findPage: function () {
            let this_ = this;
            this.utils.request.getRegionPageList(this_.filters, function (res) {
                this_.$refs.JicTable.findPage({
                    content: res.data.rows,
                    total: res.data.total
                });
            });
            // var data = [{id: 2001070006501479, merchantId: null, areaCode: "1", areaName: "1", orgId: 1909110000098882,orgName: "张小二服饰", orgCode: null}]
            // this_.$refs.JicTable.findPage({ content: data, total: 10 });
        },
        handleEdit: function (data) {
            console.log(data);
            let region = data.row;
            // debugger;
            this.areaForm.cityIds = region.cityIds;
            this.areaForm.id = region.id;
            //areaCode: '',//区域编码
            // merchantId: '',//所属商家
            // areaName: '',//区域名称
            // desc: '',
            // coverageType:1,
            // cityIds:[]
            this.areaForm.areaCode = region.areaCode;
            this.areaForm.merchantId = region.merchantId;
            this.areaForm.areaName = region.areaName;
            this.areaForm.coverageType = region.coverageType;
            // debugger;
            let provinceList = this.provinceList;
            provinceList.forEach(province => {
                // debugger;
                if (region.cityIds.indexOf(province.id + "") != -1) {
                    province.selected = true;
                } else {
                    province.selected = false;
                }
                province.children.forEach(second => {
                    if (region.cityIds.indexOf(second.id + "") != -1) {
                        second.selected = true;
                    } else {
                        second.selected = false;
                    }
                    second.children.forEach(third => {
                        if (region.cityIds.indexOf(third.id + "") != -1) {
                            third.selected = true;
                        } else {
                            third.selected = false;
                        }
                    });
                });
            });
            console.log(provinceList);
            // let provinceList = this.provinceList;
            this.areaFormVisible = true;
        },
        handleDelete: function (data) {
            if (data != null && data.params != null && data.params.length > 0) {
                let ids = data.params.map(item => item.id).toString();
                var params = {};
                params.ids = ids;
                var this_ = this;
                this.utils.request.delRegionInfo(params, function (res) {
                    if (res.code == "0000") {
                        this_.$message({
                            message: "操作成功",
                            type: "success"
                        });
                        this_.findPage(null);
                    } else {
                        this_.$message({
                            message: "操作失败, " + res.msg,
                            type: "error"
                        });
                    }
                });
            }
        },
        submitAreaForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // debugger
                    const loading = this.$loading({
                        lock: true,
                        text: "Loading",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)"
                    });
                    // alert('submit!');
                    console.log(this.areaForm);
                    let that = this;
                    this.areaForm.coverageType = this.checkAll == true ? 0 : 1;
                    this.areaForm.cityIds = this.areaForm.cityIds.join(",");
                    this.utils.request.updateRegion(this.areaForm, data => {
                        that.areaFormVisible = false;
                        that.findPage();
                        loading.close();
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        initDiaLog(flag) {
            debugger;
            let this_ = this;
            if (flag === "add") {
              this_.areaForm.cityIds = [];
              this_.areaFormVisible = true;
            }
        },
        //全国选中
        generation() {
            if (this.provinceList && this.provinceList.length > 0) {
                //一级省市选中
                for (var i = 0; i < this.provinceList.length; i++) {
                    this.checkVal(provinceList[i], this.checkAll);
                    this.provinceList[i].selected = this.checkAll;
                    this.provinceList[i].expanded = false;
                    //二级城市选中
                    var citys = this.provinceList[i].children || [];
                    for (var j = 0; j < citys.length; j++) {
                        citys[j].selected = this.checkAll;
                        this.checkVal(citys[j], this.checkAll);
                        var contys = citys[j].children || [];
                        for (var k = 0; k < contys.length; k++) {
                            contys[k].selected = this.checkAll;
                            this.checkVal(contys[k], this.checkAll);
                        }
                    }
                }
            }
        },
        //一级省市加减方法
        provinceEvent(province, provinceList) {
            var expanded = province.expanded;
            // 重置其他
            for (var i = 0; i < provinceList.length; i++) {
                provinceList[i].expanded = false;
            }
            province.expanded = !expanded;
        },
        //一级区域选中
        firstProvince(item) {
            //一级选中默认选中当前二级和三级区域
            if (item.children && item.children.length > 0) {
                for (var i = 0; i < item.children.length; i++) {
                    item.children[i].selected = item.selected;
                    //赋值
                    this.checkVal(item.children[i], item.selected);

                    if (
                        item.children[i].children &&
                        item.children[i].children.length > 0
                    ) {
                        for (var j = 0; j < item.children[i].children.length; j++) {
                            item.children[i].children[j].selected = item.selected;
                            this.checkVal(item.children[i].children[j], item.selected);
                        }
                    }
                }
            }
        },
        //二级区域选中
        secondCity(item, parentObj) {
            //二级选中默认选中当前二级下三级区域
            if (item.children && item.children.length > 0) {
                for (var i = 0; i < item.children.length; i++) {
                    item.children[i].selected = item.selected;
                }
            }
        },
        //三级区域选中
        thirdArea(item, parentObj) {
            // debugger
            this.checkVal(item, item.selected);
            var count = 0;
            if (parentObj.children && parentObj.children.length > 0) {
                //获取当前二级下所有三级是否有选中
                for (var i = 0; i < parentObj.children.length; i++) {
                    if (parentObj.children[i].selected) {
                        count++;
                    }
                }
                //有一个三级选中则选中当前二级
                if (count) {
                    parentObj.selected = true;
                } else {
                    parentObj.selected = false;
                }
            }
        },
        selectMer(data) {
            console.log(data);
            let obj = {};
            obj = this.merchantList.find(item => {
                return item.id === data;
            });
            let getName = "";
            getName = obj.name;
            console.log(getName);
            this.areaForm.merchantName = getName;
        },
        checkVal(val, boo) {
            // debugger
            let cityIds = this.areaForm.cityIds;
            if (cityIds.length == 0) {
                cityIds.push(val.id + "");
            } else {
                for (let index = 0; index < cityIds.length; index++) {
                    if (val.id + "" != cityIds[index] && boo == true) {
                        //选中
                        cityIds.push(val.id + "");
                        break;
                    } else if (val.id + "" == cityIds[index] && boo == false) {
                        //不选中
                        cityIds.splice(index, 1);
                        break;
                    }
                }
            }
            let setCityIds = new Set(cityIds);
            this.areaForm.cityIds = Array.from(setCityIds);
            console.log(cityIds);
        },
        initData() {
            const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            let that = this;
            // var areaList = [{"id":2,"code":110000,"name":"北京","parentcode":100000,"level":1,"selectAll":null,"children":[{"id":37,"code":110100,"name":"北京市","parentcode":110000,"level":2,"selectAll":null,"children":[{"id":410,"code":110101,"name":"东城区","parentcode":110100,"level":3,"selectAll":null,"children":[],"postcode":"100010"},{"id":411,"code":110102,"name":"西城区","parentcode":110100,"level":3,"selectAll":null,"children":[],"postcode":"100032"},{"id":412,"code":110105,"name":"朝阳区","parentcode":110100,"level":3,"selectAll":null,"children":[],"postcode":"100020"},{"id":413,"code":110106,"name":"丰台区","parentcode":110100,"level":3,"selectAll":null,"children":[],"postcode":"100071"}]}]},{"id":3,"code":120000,"name":"天津","parentcode":100000,"level":1,"selectAll":null,"children":[{"id":38,"code":120100,"name":"天津市","parentcode":120000,"level":2,"selectAll":null,"children":[{"id":426,"code":120101,"name":"和平区","parentcode":120100,"level":3,"selectAll":null,"children":[],"postcode":"300041"},{"id":431,"code":120106,"name":"红桥区","parentcode":120100,"level":3,"selectAll":null,"children":[],"postcode":"300131"}]},{"id":39,"code":130100,"name":"天津市1","parentcode":130000,"level":2,"selectAll":null,"children":[{"id":427,"code":120101,"name":"和平区","parentcode":130100,"level":3,"selectAll":null,"children":[]},{"id":432,"code":130106,"name":"红桥区","parentcode":130100,"level":3,"selectAll":null,"children":[],"postcode":"300131"}]}]}];
            //查询所属商家
            this.utils.request.sysUserQueryPage({
                    id: localStorage.getItem("userId")
                },
                data => {
                    // debugger
                    that.merchantList = data.data.rows[0].mMerchantList;
                    that.utils.request.getSysProvinceCityList({}, res => {
                        // that.areaFormVisible = true;
                        loading.close();

                        var areaList = res.data;
                        that.provinceList = [];
                        for (var i = 0; i < areaList.length; i++) {
                            areaList[i].expanded = false;
                            that.provinceList.push(areaList[i]);
                        }
                    });
                }
            );
        }
    }
};
</script>

<style scoped lang='scss'>
</style>
